<template>
  <!-- 使用主布局容器 -->
  <main-layout
      :username="username"
      :unread-count="unreadCount"
  >
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb mb-15">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 页面标题 -->
    <div class="page-header mb-15">
      <h2 class="page-title">个人中心</h2>
    </div>

    <!-- 个人信息卡片 -->
    <el-card class="personal-info-card mb-15" shadow="hover">
      <div slot="header" class="flex-between">
        <h3>个人信息</h3>
        <el-button
            type="primary"
            size="mini"
            @click="toggleEditMode('info')"
            :icon="isEditingInfo ? 'el-icon-check' : 'el-icon-edit'"
        >
          {{ isEditingInfo ? '保存修改' : '编辑信息' }}
        </el-button>
      </div>

      <el-form
          :model="userInfo"
          :rules="infoRules"
          ref="infoForm"
          label-width="140px"
          class="personal-info-form"
      >
        <el-row :gutter="20">
          <el-col :span="24" :md="12">
            <el-form-item label="用户编号" prop="userId">
              <el-input v-model="userInfo.userId" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userInfo.name" :disabled="!isEditingInfo"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userInfo.phone" :disabled="!isEditingInfo"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="账号状态" prop="status">
              <el-input v-model="userInfo.status" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="邮箱号" prop="email">
              <el-input v-model="userInfo.email" :disabled="!isEditingInfo"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                  v-model="userInfo.idCard"
                  :disabled="!isEditingInfo"
                  placeholder="18位身份证号"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="角色编号" prop="roleId">
              <el-input v-model="userInfo.roleId" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="userInfo.roleName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 密码修改卡片 -->
    <el-card class="password-card" shadow="hover">
      <div slot="header">
        <h3>修改密码</h3>
      </div>

      <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordForm"
          label-width="140px"
          class="password-form"
      >
        <el-row :gutter="20">
          <el-col :span="24" :md="16">
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="请输入当前密码"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="16">
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="新密码至少8位，包含字母和数字"
                  @input="validatePasswordStrength"
              ></el-input>
              <div v-if="passwordForm.newPassword" class="password-strength mt-2">
                <div class="strength-label">密码强度：</div>
                <div class="strength-bars">
                  <div
                      class="strength-bar"
                      :class="passwordStrength >= 1 ? 'active' : ''"
                      :style="{ backgroundColor: passwordStrength >= 1 ? getStrengthColor(1) : '' }"
                  ></div>
                  <div
                      class="strength-bar"
                      :class="passwordStrength >= 2 ? 'active' : ''"
                      :style="{ backgroundColor: passwordStrength >= 2 ? getStrengthColor(2) : '' }"
                  ></div>
                  <div
                      class="strength-bar"
                      :class="passwordStrength >= 3 ? 'active' : ''"
                      :style="{ backgroundColor: passwordStrength >= 3 ? getStrengthColor(3) : '' }"
                  ></div>
                </div>
                <div class="strength-text">{{ getStrengthText() }}</div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="16">
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" :md="16" class="form-actions">
            <el-button
                type="primary"
                @click="submitPasswordChange"
                :loading="passwordLoading"
            >
              确认修改
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 成功提示对话框 -->
    <el-dialog
        title="操作成功"
        :visible.sync="successDialogVisible"
        width="300px"
        :close-on-click-modal="false"
        :show-close="false"
    >
      <div class="success-content flex-center">
        <el-icon class="success-icon"><success-filled /></el-icon>
        <p class="success-message">{{ successMessage }}</p>
      </div>
      <div slot="footer" class="dialog-footer flex-center">
        <el-button type="primary" @click="handleSuccessConfirm">确定</el-button>
      </div>
    </el-dialog>
  </main-layout>
</template>

<script>
import MainLayout from '../../components/layout/MainLayout.vue';

export default {
  components: {
    MainLayout,
  },
  data() {
    // 密码验证规则：至少8位，包含字母和数字
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (value.length < 8) {
        callback(new Error('密码长度至少8位'));
      } else if (!/[A-Za-z]/.test(value) || !/\d/.test(value)) {
        callback(new Error('密码必须包含字母和数字'));
      } else {
        callback();
      }
    };

    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认新密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      username: '管理员',
      unreadCount: 3,
      isEditingInfo: false,
      userInfo: {
        userId: 'USR001',
        name: '张系统',
        phone: '13800138001',
        status: '默认',
        email: 'sys.zhang@example.com',
        idCard: '110101199001011234',
        roleId: 'ROL001',
        roleName: '系统管理员'
      },
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordStrength: 0,
      passwordLoading: false,
      successDialogVisible: false,
      successMessage: '',
      // 个人信息验证规则
      infoRules: {
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱号', trigger: 'blur' },
          { pattern: /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /^\d{18}$/, message: '请输入18位身份证号', trigger: 'blur' }
        ]
      },
      // 密码修改验证规则
      passwordRules: {
        currentPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', validator: validateConfirmPassword }
        ]
      }
    };
  },
  methods: {
    // 切换个人信息编辑模式
    toggleEditMode(type) {
      if (type === 'info') {
        if (this.isEditingInfo) {
          // 保存修改
          this.$refs.infoForm.validate((valid) => {
            if (valid) {
              // 模拟API请求
              setTimeout(() => {
                this.isEditingInfo = false;
                this.successMessage = '个人信息修改成功';
                this.successDialogVisible = true;
              }, 500);
            }
          });
        } else {
          // 进入编辑模式
          this.isEditingInfo = true;
        }
      }
    },

    // 验证密码强度
    validatePasswordStrength() {
      const password = this.passwordForm.newPassword;
      if (!password) {
        this.passwordStrength = 0;
        return;
      }

      let strength = 0;

      // 长度检查
      if (password.length >= 8) strength++;
      if (password.length >= 12) strength++;

      // 复杂度检查
      const hasLetter = /[A-Za-z]/.test(password);
      const hasNumber = /\d/.test(password);
      const hasSpecial = /[^A-Za-z0-9]/.test(password);

      if (hasLetter && hasNumber) strength++;
      if (hasSpecial) strength++;

      // 限制最大强度为3
      this.passwordStrength = Math.min(strength, 3);
    },

    // 获取密码强度颜色
    getStrengthColor(level) {
      const colors = ['#ff4d4f', '#faad14', '#52c41a'];
      return colors[level - 1] || '#ccc';
    },

    // 获取密码强度文本描述
    getStrengthText() {
      const texts = ['弱', '中', '强'];
      return texts[this.passwordStrength - 1] || '';
    },

    // 提交密码修改
    submitPasswordChange() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          // 模拟验证当前密码
          if (this.passwordForm.currentPassword !== 'Sys@123456') {
            this.$message.error('当前密码输入错误');
            return;
          }

          // 模拟API请求
          this.passwordLoading = true;
          setTimeout(() => {
            this.passwordLoading = false;
            this.passwordForm = {
              currentPassword: '',
              newPassword: '',
              confirmPassword: ''
            };
            this.passwordStrength = 0;
            this.successMessage = '密码修改成功，请重新登录';
            this.successDialogVisible = true;
          }, 800);
        }
      });
    },

    // 处理成功提示确认
    handleSuccessConfirm() {
      this.successDialogVisible = false;
      // 如果是密码修改成功，跳转到登录页
      if (this.successMessage.includes('密码修改成功')) {
        this.$router.push('/login');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

// 表单样式
.personal-info-form, .password-form {
  margin-top: 20px;
}

// 密码强度样式
.password-strength {
  display: flex;
  align-items: center;

  .strength-label {
    font-size: 13px;
    color: $text-secondary;
    margin-right: 8px;
    white-space: nowrap;
  }

  .strength-bars {
    display: flex;
    gap: 4px;
    flex: 1;
    max-width: 150px;
  }

  .strength-bar {
    height: 6px;
    flex: 1;
    background-color: #e5e5e5;
    border-radius: 3px;
    transition: all 0.3s ease;
  }

  .strength-bar.active {
    background-color: #52c41a;
  }

  .strength-text {
    font-size: 13px;
    margin-left: 8px;
    color: $text-secondary;
  }
}

// 表单按钮区域
.form-actions {
  margin-top: 15px;
}

// 卡片样式
.personal-info-card, .password-card {
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }
}

.personal-info-card {
  margin-bottom: 20px;
}

// 成功提示对话框样式
.success-content {
  padding: 20px 0;

  .success-icon {
    font-size: 48px;
    color: #52c41a;
    margin-right: 15px;
  }

  .success-message {
    font-size: 16px;
    color: $text-primary;
  }
}

.dialog-footer {
  padding: 10px 20px 20px;
}

// 响应式调整
@media (max-width: 768px) {
  .password-form {
    .el-form-item {
      width: 100%;
    }
  }

  .strength-bars {
    max-width: 100px;
  }
}
</style>
